//
//  BottomMenu.swift
//  QQZone
//
//  Created by hjj on 2016/12/3.
//  Copyright © 2016年 hjjuny. All rights reserved.
//


import UIKit

enum BottomMenuType : Int {
    case mood = 0
    case photo = 1
    case blog = 2
}

class BottomMenu: UIView {
    
    // MARK: 属性
    var itemClickCallback : ((_ type : BottomMenuType) -> ())?
    
    // MARK: 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupItem("tabbar_mood", .mood)
        setupItem("tabbar_photo", .photo)
        setupItem("tabbar_blog", .blog)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

// MARK:- 添加子控件的方法
extension BottomMenu {
    fileprivate func setupItem(_ iconName : String, _ type : BottomMenuType) {
        let item = UIButton()
        
        item.setImage(UIImage(named: iconName), for: .normal)
        item.setBackgroundImage(UIImage(named: "tabbar_separate_selected_bg"), for: .highlighted)
        item.tag = type.rawValue
        
        item.addTarget(self, action: #selector(itemClick(_:)), for: .touchUpInside)
        
        addSubview(item)
    }
    
    @objc private func itemClick(_ item : UIButton) {
        if let callback = itemClickCallback {
            callback(BottomMenuType(rawValue: item.tag)!)
        }
    }
}

// MARK:- 对外提供的函数
extension BottomMenu {
    func setupCurrentOritation(_ isLandscape : Bool) {
        // 0.获取子控件个数
        let count = subviews.count
        
        // 1.调整自身的frame
        let w : CGFloat = superview!.frame.width
        let h : CGFloat = isLandscape ? kDockItemH : CGFloat(count) * kDockItemH
        let x : CGFloat = 0
        let y : CGFloat = superview!.frame.height - h
        frame = CGRect(x: x, y: y, width: w, height: h)
        
        // 2.调整子控件的frame
        for (index, item) in subviews.enumerated() {
            let itemW : CGFloat = isLandscape ? w / CGFloat(count) : w
            let itemH : CGFloat = isLandscape ? h : kDockItemH
            let itemX : CGFloat = isLandscape ? CGFloat(index) * itemW : 0
            let itemY : CGFloat = isLandscape ? 0 : CGFloat(index) * itemH
            item.frame = CGRect(x: itemX, y: itemY, width: itemW, height: itemH)
        }
    }
}
